package com.luban.springcloud.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.luban.springcloud.pojo.User;

@RestController
@RequestMapping("/user")
public class UserConsumerController {
	
	//static final String PROVIDER_URL = "http://localhost:5000/user";
	//ribbon调用
	static final String PROVIDER_URL = "http://luban-provider/user";
	
	@Autowired
	private	RestTemplate restTemplate;
	
	//引入eureka和jackson，从源码看jackson里返回xml高于json
	@GetMapping(value="/get/{id}",produces = {"application/json;charset=UTF-8"})
	public User get(@PathVariable("id")Integer id) {
		return restTemplate.getForObject(PROVIDER_URL+"/get/"+id, User.class);
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	public List<User> list() {
		return restTemplate.getForObject(PROVIDER_URL+"/list", List.class);
	}

	@PostMapping(value="/adOrUp")
	public String addOrUpdateUser(User user) {
		return	restTemplate.postForObject(PROVIDER_URL+"/adOrUp", user, String.class);
	}
	
	@GetMapping(value="/delete/{id}")
	public boolean delete(@PathVariable("id")Integer id) {
		try {
			restTemplate.getForObject(PROVIDER_URL+"/delete/"+id, Boolean.class);
			return true; 
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping(value="/getTestInfo")
	public Map<String,Object> getTestInfo(){
	    return restTemplate.getForObject(PROVIDER_URL+"/getTestInfo/", Map.class);
	}
}
